<template>
  <el-dialog :model-value="visible" :title="title" width="500" :close-on-click-modal="false" :show-close="false">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
      <el-form-item label="产品" prop="productCode">
        <zw-select :data="productList" label-key="name" value-key="code" v-model:label="form.productName"
          v-model:value="form.productCode"></zw-select>
      </el-form-item>
      <el-form-item label="SN" prop="productSn">
        <el-input v-model="form.productSn"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="comment">
        <el-input type="textarea" :row="4" v-model="form.comment"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="emits('close')">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type { CreateOrderProductVO } from '@/server/afterSale/types';
import ZwSelect from '@/components/Form/ZwSelect.vue';
import ApiTree from '@/server/api-tree';
import { DictTypeEnum, type DictVO } from '@/server/dict/types';
import type { FormInstance, FormRules } from 'element-plus';
import { reactive, ref, watch } from 'vue';

const emits = defineEmits(["close", "save"])
const props = withDefaults(defineProps<{ visible: boolean, data: CreateOrderProductVO | null }>(), {
  visible: false,
  data: null
});
const title = ref<string>("添加产品");
const form = ref<CreateOrderProductVO>({
  productCode: "",
  productName: "",
  productSn: "",
  guid: "",
  comment: ""
});
const formRef = ref<FormInstance>();
const formRules = reactive<FormRules<CreateOrderProductVO>>({
  productCode: [{ required: true, message: "产品不能为空" }],
  productSn: [{ required: true, message: "SN不能为空" }],
  comment: [{ required: true, message: "备注不能为空" }],
})
const initForm = () => {
  form.value = {
    productCode: "",
    productName: "",
    productSn: "",
    guid: "",
    comment: ""
  }
}
const productList = ref<DictVO[]>([])
const getProductList = async () => {
  const { success, data } = await ApiTree.dict.list(DictTypeEnum.PRODUCT, true);
  if (success) {
    productList.value = data;
  }
}
const submit = () => {
  if (!form.value.guid) {
    form.value.guid = Date.now().toString();
  }
  formRef.value?.validate((valid => {
    if (valid) {
      emits("save", form.value);
    }
  }))
}
watch(() => props.visible, () => {
  if (props.visible) {
    title.value = props.data ? `编辑产品` : "添加产品";
    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    props.data ? form.value = { ...props.data } : initForm();
    getProductList();
  }
})
</script>
<style lang="scss" scope></style>
